from flask import Blueprint, request, jsonify
from .Cmod import *
from .Cmod_pic import *
from .Cmod_user import *
from .Cmod_express import *

blue_user = Blueprint('users', __name__)


# 用户注册
@blue_user.route('/api/enroll', methods=['POST', 'GET'])
def enroll_user():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    # 获取前端发送的数据
    data = request.json
    # print(data)
    if data is None:
        return {'message': '无效的请求格式'}, 400
    # print(data, type(data))
    user_number = data.get('user_number')
    user_password = data.get('user_password')
    # print(user_number, user_password, 1)
    # 检查用户编号是否已存在
    if Users.query.filter_by(user_number=user_number).first():
        return {'message': '用户编号已存在'}, 201
    max_id = get_max_user_id()
    # 其他参数可选，如果没有提供，将使用默认值 None
    user_fan = data.get('user_fan')
    user_attention = data.get('user_attention')
    user_state = data.get('user_state')
    user_introduce = data.get('user_introduce')
    user_fraction = data.get('user_fraction')
    user_grade = data.get('user_grade', 0)
    is_active = data.get('is_active')
    user_upgrade = 0
    new_user = Users(
        user_name=f"体验官-000000{max_id}",
        user_number=user_number,
        user_password=user_password,
        user_fan=user_fan,
        user_attention=user_attention,
        user_state=user_state,
        user_introduce=user_introduce,
        user_fraction=user_fraction,
        user_grade=user_grade,
        is_active=is_active,
        user_upgrade=user_upgrade,
        user_gender="未知"
    )
    # 将新用户添加到数据库
    db.session.add(new_user)
    db.session.commit()
    # 获取新创建的用户id，来设置默认头像
    user_id = Users.query.filter_by(user_number=user_number).first()
    # https: // the - design - lifetime.oss - cn - beijing.aliyuncs.com / base.png
    # creat_pic(["https://gd-hbimg.huaban.com/7968f776596196a8061e9ee0ee51c0606d785fc42400b-9aWWPH_fw236"],
    #           "user", user_id.user_id)
    creat_pic(["https://the-design.oss-cn-beijing.aliyuncs.com/base.png"],
              "user", user_id.user_id)
    # 登录成功
    user_id = Users.query.filter_by(user_number=user_number).first()
    pic = Picture.query.filter_by(picture_object=user_id.user_id, picture_ob_type="user").first()
    user_data = {
        'user_id': user_id.user_id,
        'user_name': user_id.user_name,
        'user_number': user_id.user_number,
        'user_password': user_id.user_password,
        'user_fan': user_id.user_fan,
        'user_attention': user_id.user_attention,
        'user_state': user_id.user_state,
        'user_introduce': user_id.user_introduce,
        'user_fraction': user_id.user_fraction,
        'user_grade': user_id.user_grade,
        'is_active': user_id.is_active,
        'picture_address': pic.picture_address,
        'picture_id': pic.picture_id,
        'message': '用户注册成功'
    }
    return jsonify(user_data)


# 用户登入
@blue_user.route('/api/login', methods=['POST', 'GET'])
def login():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    if data is None:
        return {'message': '无效的请求格式'}, 400

    # {"user_number": "user1", "user_password": "pass1"}
    user_number = data.get('user_number')
    user_password = data.get('user_password')
    # 验证用户凭证
    if validate_user(user_number, user_password):
        # 登录成功
        user_id = Users.query.filter_by(user_number=user_number).first()
        pic = Picture.query.filter_by(picture_object=user_id.user_id, picture_ob_type="user").first()
        # print(pic)

        dis = Discord.query.filter_by(discord_user=user_id.user_id,
                                      discord_state=True).all()
        user_data = {
            'user_id': user_id.user_id,
            'user_name': user_id.user_name,
            'user_number': user_id.user_number,
            'user_password': user_id.user_password,
            'user_fan': user_id.user_fan,
            'user_attention': user_id.user_attention,
            'user_state': user_id.user_state,
            'user_introduce': user_id.user_introduce,
            'user_fraction': user_id.user_fraction,
            'user_grade': user_id.user_grade,
            'is_active': user_id.is_active,
            'picture_address': pic.picture_address,
            'picture_id': pic.picture_id,
            'message': '登录成功',
            'discord_number': len(dis),
            'user_upgrade': user_id.user_upgrade
        }
        # print(user_data)
        return jsonify(user_data), 200
    else:
        # 登录失败
        return {'message': '登录失败'}, 400


# 用户注销
@blue_user.route('/api/logout', methods=['POST', 'GET'])
def logout():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    # print(data)
    user_id = data.get('user_id')
    user = Users.query.filter_by(user_id=user_id).first()
    user.is_active = False
    db.session.commit()
    print("用户下线")
    return {'message': f'{user.user_name}下线'}, 200


# 用户修改个人信息汇总
@blue_user.route('/api/change/user/all', methods=['POST', 'GET'])
def change_user_all():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.json
    user_id = data.get('user_id')
    user_now = Users.query.filter_by(user_id=user_id).first()
    user_pic_now = Picture.query.filter_by(picture_object=user_id, picture_ob_type="user").first()
    user_pic = data.get('user_pic', 0)
    if user_pic != 0:
        user_pic_now.picture_address = user_pic
    user_introduce = data.get('user_introduce', 0)
    if user_introduce != 0:
        user_now.user_introduce = user_introduce
    user_name = data.get('user_name', 0)
    if user_name != 0:
        user_now.user_name = user_name
    user_gender = data.get('user_gender', 0)
    if user_gender != 0:
        user_now.user_gender = user_gender
    user_birthday = data.get('user_birthday', 0)
    if user_birthday != 0:
        user_now.user_birthday = user_birthday
    user_city = data.get('user_city', 0)
    if user_city != 0:
        user_now.user_city = user_city
    user_province = data.get('user_province', 0)
    if user_province != 0:
        user_now.user_province = user_province

    db.session.commit()
    return {'message': '修改成功'}, 200


# 用户修改密码
@blue_user.route('/api/change_password', methods=['POST', 'GET'])
def change_password():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('user_id')
    user_password = data.get('user_password')
    user = Users.query.filter_by(user_id=user_id).first()
    user.user_password = user_password
    db.session.commit()
    return {'message': '修改密码成功'}, 200


# 用户修改头像
@blue_user.route('/api/change_picture', methods=['POST', 'GET'])
def change_picture():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('user_id')
    picture_address = data.get('picture_address')
    pic = Picture.query.filter_by(picture_object=user_id, picture_ob_type="user").first()
    pic.picture_address = picture_address
    db.session.commit()
    return {'message': '修改头像成功'}, 200


# 用户修改简介
@blue_user.route('/api/change_introduce', methods=['POST', 'GET'])
def change_introduce():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('user_id')
    user_introduce = data.get('user_introduce')
    user = Users.query.filter_by(user_id=user_id).first()
    user.user_introduce = user_introduce
    db.session.commit()
    return {'message': '修改简介成功'}, 200


# 用户增删黑名单
@blue_user.route('/api/add/blacklist', methods=['POST', 'GET'])
def blacklist():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 400
    data = request.get_json()
    user_id = data.get('user_id')
    user_type = data.get('type')
    blacklist_id = data.get('blacklist_id')
    if user_type == "add":
        blt = Blacklist(
            blacklist_parent=user_id,
            blacklist_child=blacklist_id
        )
        db.session.add(blt)
        db.session.commit()
        return {'message': '添加黑名单成功'}, 200
    elif user_type == "less":
        blt = Blacklist.query.filter_by(blacklist_parent=user_id,
                                        blacklist_child=blacklist_id).first()
        db.session.delete(blt)
        db.session.commit()
        return {'message': '删除黑名单成功'}, 200
    else:
        return {'message': '未识别的type字符串'}, 400


# 用户增删关注和粉丝
@blue_user.route('/api/add/attention', methods=['POST', 'GET'])
def attention():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 400
    data = request.get_json()
    user_id = data.get('user_id')
    user_for = data.get('user_for')
    user_type = data.get('type')
    if user_type == "add":
        # 增加关注对象
        attention_now = AttentionFan(
            af_parent=user_id,
            af_child=user_for
        )
        db.session.add(attention_now)
        user_for_fan = Users.query.filter_by(user_id=user_for).first()
        user_for_fan.user_fan += 1
        user_attention = Users.query.filter_by(user_id=user_id).first()
        user_attention.user_attention += 1
        db.session.commit()
        return {'message': '关注成功'}, 200

    elif user_type == "less":
        # 取消关注
        af = AttentionFan.query.filter_by(af_parent=user_id, af_child=user_for).first()
        db.session.delete(af)
        user_for_fan = Users.query.filter_by(user_id=user_for).first()
        user_for_fan.user_fan -= 1
        user_attention = Users.query.filter_by(user_id=user_id).first()
        user_attention.user_attention -= 1
        db.session.commit()
        return {'message': '取关成功'}, 200

    else:
        return {'message': '未识别的type字符串'}, 400


# 用户黑名单
@blue_user.route('/api/blacklist', methods=['POST', 'GET'])
def get_blacklist():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 400
    data = request.get_json()
    user_id = data.get('user_id')
    user_type = data.get('type')
    if user_type == "blacklist":
        # 获取黑名单列表
        blacklists = Blacklist.query.filter_by(blacklist_parent=user_id).all()
        blacklists_data = []
        for bli in blacklists:
            user_now = Users.query.filter_by(user_id=bli.blacklist_child).first()
            pic = Picture.query.filter_by(picture_ob_type='user', picture_object=bli.blacklist_child).first()

            black_data = {
                'blacklist_id': bli.blacklist_child,
                'user_pic': pic.picture_address,
                'user_name': user_now.user_name,
                'user_fan': user_now.user_fan,
                'user_attention': user_now.user_attention,
                'user_introduce': user_now.user_introduce,
                'user_fraction': user_now.user_fraction,
                'user_upgrade': user_now.user_upgrade,
                'user_birthday': user_now.user_birthday,
                'user_city': user_now.user_city,
                'user_province': user_now.user_province,
            }
            blacklists_data.append(black_data)
        return jsonify({'data': blacklists_data}), 200
    else:
        return {'message': '未识别的type字符串'}, 400


# 用户增删点赞
@blue_user.route('/api/type/like', methods=['POST', 'GET'])
def query_type_like():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 400
    data = request.get_json()
    object_id = data.get('object_id')
    object_type = data.get('object_type')
    user_id = data.get('id')
    type_now = data.get('type')
    if type_now == "add":
        ql = Like.query.filter_by(like_user=user_id, like_object=object_id, like_type=object_type).first()
        if ql is not None:
            return {'message': '用户已点赞该项目'}, 201
        like_now = Like(
            like_user=user_id,
            like_object=object_id,
            like_type=object_type
        )
        db.session.add(like_now)
        db.session.commit()
        return {'message': '点赞成功'}, 200
    elif type_now == "less":
        ql = Like.query.filter_by(like_user=user_id, like_object=object_id, like_type=object_type).first()
        if ql is None:
            return {'message': '用户未点赞该项目'}, 201
        db.session.delete(ql)
        db.session.commit()
        return {'message': '取消点赞成功'}, 200
    else:
        return {'message': '未识别的type字符串'}, 201


# 新增用户历史记录
@blue_user.route('/api/history/add', methods=['POST', 'GET'])
def add_history():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 400
    data = request.json
    user_id = int(data.get('user_id', 0))
    content = data.get('content')
    object_id = int(data.get('object_id', 0))
    for_id = int(data.get('for_id', 0))
    if user_id == 0:
        return {'message': 'user_id不能为空'}, 400
    text_now = str(user_id) + ' ' + content + ' '
    if object_id != 0:
        text_now = text_now + str(object_id)
        if for_id != 0:
            text_now = text_now + 'is' + str(for_id)
    else:
        if for_id != 0:
            text_now = text_now + str(for_id)
    history_now = History(
        history_user=user_id,
        history_text=text_now
    )
    db.session.add(history_now)
    db.session.commit()
    return {'message': '用户历史记录添加成功'}, 200


# 渲染用户的关注粉丝列表
@blue_user.route('/api/attention', methods=['POST', 'GET'])
def get_attention():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 400
    data = request.get_json()
    user_id = data.get('user_id')
    user_type = data.get('type')
    page_num = int(data.get('page_num', 0))

    if user_type == "fan":
        # 获取粉丝列表
        fans = AttentionFan.query.filter_by(af_child=user_id).all()
        fans_data = []
        for fan in fans:
            user_id = fan.af_parent
            user = Users.query.filter_by(user_id=user_id).first()
            user_now = {
                'user_name': user.user_name,
                'user_id': user.user_id,
                'user_fan': user.user_fan,
                'user_attention': user.user_attention,
                'user_introduce': user.user_introduce,
                'user_fraction': user.user_fraction,
                'user_grade': user.user_grade,
                'user_gender': user.user_gender,
                'user_birthday': user.user_birthday,
                'user_city': user.user_city,
                'user_province': user.user_province,
                'user_pic': get_user_pic_url(user.user_id)
            }
            fans_data.append(user_now)
        if page_num:
            page_now = int(data.get('page', 1) - 1) * page_num
            num = inquire_total_page(len(fans_data), page_num)

            if page_now >= len(fans_data):
                fans_data = []
            else:

                fans_data = get_page_data(fans_data, data.get('page', 1), page_num)

            response = {
                'fans_data': fans_data,
                'total_page': num
            }
            return jsonify(response)
        # 将粉丝数据转换为字典列表
        response = {
            'data': fans_data
        }
        print("粉丝数据发送")
        return jsonify(response), 200
    elif user_type == "attention":
        # 获取关注列表
        attentions = AttentionFan.query.filter_by(af_parent=user_id).all()
        attentions_data = []
        for attention in attentions:
            user_id = attention.af_child
            user = Users.query.filter_by(user_id=user_id).first()
            user_now = {
                'user_name': user.user_name,
                'user_id': user.user_id,
                'user_fan': user.user_fan,
                'user_attention': user.user_attention,
                'user_introduce': user.user_introduce,
                'user_fraction': user.user_fraction,
                'user_grade': user.user_grade,
                'user_gender': user.user_gender,
                'user_birthday': user.user_birthday,
                'user_city': user.user_city,
                'user_province': user.user_province,
                'user_pic': get_user_pic_url(user.user_id)
            }
            attentions_data.append(user_now)

        if page_num:
            page_now = int(data.get('page', 1)) * page_num
            num = inquire_total_page(len(attentions_data), page_num)

            if page_now >= len(attentions_data):
                attentions_data = []
            else:
                attentions_data = attentions_data[page_now:page_now + page_num]
            response = {
                'attentions_data': attentions_data,
                'total_page': num
            }
            return jsonify(response)
        # 将关注数据转换为字典列表
        response = {
            'data': attentions_data
        }
        print("关注数据发送")
        return jsonify(response), 200
    else:
        return {'message': '未识别的type字符串'}, 400


# 展示用户的主页:用户的所有信息，头像，历史记录，粉丝数，关注数
@blue_user.route('/api/show/user', methods=['POST', 'GET'])
def get_user_info():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('user_id')
    user = Users.query.filter_by(user_id=user_id).first()
    user_pics = Picture.query.filter_by(picture_ob_type='user', picture_object=user_id).first()
    user_now = {
        'user_id': user.user_id,
        'user_name': user.user_name,
        'user_introduce': user.user_introduce,
        'user_attention': user.user_attention,
        'user_fan': user.user_fan,
        'user_grade': user.user_grade,
        'user_upgrade': user.user_upgrade,
        'user_gender': user.user_gender,
        'user_birthday': user.user_birthday,
        'user_city': user.user_city,
        'user_province': user.user_province,
        'user_pic': user_pics.picture_address
    }
    history = History.query.filter_by(history_user=user_id).all()
    history_list = [
        {
            'history_id': history_now.history_id,
            'history_user': history_now.history_user,
            'history_text': history_now.history_text,
            'history_time': history_now.history_time.strftime('%Y-%m-%d %H:%M:%S'),
        } for history_now in history
    ]
    response = {
        'user_now': user_now,
        'history_list': history_list
    }
    return jsonify(response), 200


# 查找用户发布过的回答(该用户发布的问题下的一级评论)
@blue_user.route('/api/user/answer', methods=['POST', 'GET'])
def get_question_answer():
    data = request.get_json()
    review_user = data.get('user_id')
    review_now = Review.query.filter_by(review_object_type='question',
                                        review_user=review_user,
                                        review_grade_top=None).all()
    if review_now is None:
        return {'message': '当前用户还没有回答'}
    review_list = []
    for review_now1 in review_now:
        question_now = QuestionRelation.query.filter_by(querelation_review=review_now1.review_id).first()
        if question_now is None:
            review_adopt = False
        else:
            review_adopt = True
        question = Questions.query.filter_by(question_id=review_now1.review_object_id).first()
        review_data = {
            'question_title': question.question_title,
            'question_id': question.question_id,
            'question_text': question.question_text,
            'question_time': question.question_time.strftime('%Y-%m-%d %H:%M:%S'),
            'review_id': review_now1.review_id,
            'review_text': review_now1.review_text,
            'review_time': review_now1.review_time.strftime('%Y-%m-%d %H:%M:%S'),
            'review_adopt': review_adopt
        }
        review_list.append(review_data)
    response = {
        'review_list': review_list
    }
    return jsonify(response)
